/// <reference path="_all.ts" />

module Application.Routing {

    export class Router {
        
        public static $inject = [
            '$routeProvider',
            '$locationProvider',
            '$httpProvider',
        ];

        constructor(routeProvider: ng.route.IRouteProvider, locationProvider: ng.ILocationProvider, httpProvider: ng.IHttpProvider) {           
            routeProvider
                .when("/servers", {
                    controller: 'ServersController',
                    templateUrl: './views/servers.html',
                    caseInsensitiveMatch: true,
                    access: 14,
                })
                .when("/server/:server_id", {
                    controller: 'ServerController',
                    templateUrl: './views/server.html',
                    caseInsensitiveMatch: true,
                    access: 14,
                })
                .when("/actions", {
                    controller: 'ActionsController',
                    templateUrl: './views/actions.html',
                    caseInsensitiveMatch: true,
                    access: 14,
                })
                .when("/actions/:server_id", {
                    controller: 'ActionsController',
                    templateUrl: './views/actions.html',
                    caseInsensitiveMatch: true,
                    access: 14,
                })
                .when("/members/:server_id", {
                    controller: 'MembersController',
                    templateUrl: './views/members.html',
                    caseInsensitiveMatch: true,
                    access: 14,
                })
                .when("/players", {
                    controller: 'PlayersController',
                    templateUrl: './views/players.html',
                    caseInsensitiveMatch: true,
                    access: 14,
                })
                .when("/users", {
                    controller: 'UsersController',
                    templateUrl: './views/users.html',
                    caseInsensitiveMatch: true,
                    access: 8,
                })
                .when("/users/:user_id", {
                    controller: 'UserController',
                    templateUrl: './views/user.html',
                    caseInsensitiveMatch: true,
                    access: 14,
                })
                .otherwise({
                    redirectTo: '/login',
                    controller: 'LoginController',
                    templateUrl: './views/login.html',
                    caseInsensitiveMatch: true,
                    access: 0,
                });
            
            var interceptor = ['$location', '$q', function (location: ng.ILocationService, q: ng.IQService) {
                function success(response) {
                    return response;
                }
                function error(response) {
                    if (response.status === 401) {
                        console.log('Interceptor Reject - Unauthorized - Redirect to login');
                        location.path('/login');
                        return q.reject(response);
                    }
                    else {
                        console.log('Interceptor Reject');
                        return q.reject(response);
                    }
                }
                return function (promise) {
                    return promise.then(success, error);
                }
            }];
            httpProvider.responseInterceptors.push(interceptor);
        }
    };

    export class RouteChangeHandler {

        public static $inject = [
            '$rootScope',
            '$location',
            '$route',
        ];

        constructor(rootScope: Application.Interfaces.Scopes.IRootScope, location: ng.ILocationService, route: ng.route.IRouteService) {
            if (rootScope.user == null) {
                rootScope.user = <Application.Resources.IUser>{};
                rootScope.user.login = '';
                rootScope.user.user_id = 0;
                rootScope.user.is_active = false;
                rootScope.user.role = 0;
            };
            if (rootScope.user && rootScope.user.role == null) {
                rootScope.user.role = 0;
            };
            rootScope.$on("$routeChangeStart", function (event, next, current) {
                if (!next.access || (next.access > 0 && !(next.access & rootScope.user.role))) {
                    if (rootScope.user.role > 0) {
                        var url = location.path();
                        location.path(current.originalPath);
                    }
                    else {
                        location.path('/login');
                    }
                }
            });
        }
    };

    export class LocationChangeHandler {

        public static $inject = [
            '$rootScope',
            '$location',
            '$route',
        ];

        constructor(rootScope: Application.Interfaces.Scopes.IRootScope, location: ng.ILocationService, route: ng.route.IRouteService) {
            if (rootScope.user == null) {
                rootScope.user = <Application.Resources.IUser>{};
                rootScope.user.login = '';
                rootScope.user.user_id = 0;
                rootScope.user.is_active = false;
                rootScope.user.role = 0;
            };
            if (rootScope.user && rootScope.user.role == null) {
                rootScope.user.role = 0;
            };
            rootScope.$on("$locationChangeStart", function (event, next, current) {
                var curr = <any>route.current;
                var url = location.path();
                var nextRoute = null;
                if (route != null && route.routes != null) {
                    var routes = Object.keys(route.routes);
                    for (var i = 0; i < routes.length; i++) {
                        var key = routes[i];
                        if (route.routes[key] && route.routes[key].regexp && route.routes[key].regexp.test(url)) {
                            nextRoute = route.routes[key];
                            break;
                        };
                    };
                };             
                if (nextRoute != null && (!nextRoute.access || (nextRoute.access > 0 && !(nextRoute.access & rootScope.user.role)))) {
                    if (rootScope.user.role > 0) {
                        event.preventDefault();
                        //location.path(current);
                    }
                    else {
                        location.path('/login');
                    }
                }
            });
        }
    };

}